(function (exports, global) {
		var util = exports;
		util.version = '0.1';
		var totalCount = 0;
		util.updateUnreadCount = function(id,isClick){
            if(!isClick){
                $("#chatListColumn_"+id).find(".amsgNum").text(parseInt($("#chatListColumn_"+id).find(".amsgNum").text())+1).show();
                totalCount = totalCount + 1;
            }else{
                var count = parseInt($("#chatListColumn_"+id).find(".amsgNum").text());
                $("#chatListColumn_"+id).find(".amsgNum").text(0).hide();
                totalCount = totalCount - count;
            }
            if(totalCount>0){
					$(".msgNum").text(totalCount).show();
			}else{
				totalCount = 0;
				$(".msgNum").text(0).hide();
			}
        };
		util.groupSetUphide = function(){
			$(".groupSetUp").animate({
		        "width": 0
		    }, 200);
		};

		util.matchURL = function(metext){
			
			//检索邮箱
			var mail=metext.match(/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/g);
			if(mail){
				metext=metext.replace(mail,'<a href="mailto:'+mail+'">'+mail+'</a>');
				return metext;
			}else{
			//检索url
			var url=metext.match(/(?:http\S?:\/\/)?[A-Za-z0-9_\-]+(?:\.[A-Za-z0-9_\-]+)*\.[a-zA-Z]{2,}(?:\/[^\/]*)*$/g);
				if(url){
						metext=metext.replace(url,'<a target="_black" href="http://'+url+'">'+url+'</a>');
						return metext;
				}
			}
		};
	    util.compileExpression = function(metext){
	    	//检索EMOJI表情
			/*var emojiObj2 = metext.match(/\<(.*?)\>/g);
			if (emojiObj2) {
				$.each(emojiObj2, function(d, value) {
					for (var key in emojiJson) {
						if (value == key) {
							metext = metext.replace(value,'<span class="emoji '+emojiJson[value]+'"></span>');
							return metext;
						}
					}
				});
			}*/
			
			//检索邮箱
			var mails=metext.match(/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/g);
			if(mails){
				$.each(mails,function(index,mail){
					if(mail){
						metext=metext.replace(mail,'<a href="mailto:'+mail+'">'+mail+'</a>');
						return metext;
					}
				});
			}
			//检索url
            var _urls=metext.match(/(?:http\S?:\/\/)?[A-Za-z0-9_\-]+(?:\.[A-Za-z0-9_\-]+)[^@\>]*\.[a-zA-Z]{2,}(?:\/[^\/]*)*/);
            if(_urls){
                $.each(_urls,function(index, url){
                    if(url){
                        var newUrl = '';
                        if(url.indexOf('http://') > -1 || url.indexOf('https://') > -1){
                            newUrl = url;
                        }else{
                            newUrl = 'https://'.concat(url);
                        }
                        metext=metext.replace(url,'<a target="_black" href="'+newUrl+'">'+url+'</a>');
                        return metext;
                    }
                });
            }
		    //匹配at消息
            /*
            var atContacts = metext.match(/^@[a-zA-Z0-9_\u4e00-\u9fa5]+$/g);
            if(atContacts){
                $.each(atContacts, function(index, atContact){
                    if(!atContact) return;
                    metext=metext.replace(atContact,'<a href="javascript:void(0)">'+atContact+'</a>');
                    return metext;
                });
            }
            */

	    	//检索QQ表情
			var emojiObj = metext.match(/\[(.*?)\]/g);
			if (emojiObj) {
				$.each(emojiObj, function(d, value) {
					for (var key in emojiJson) {
						if (value == key) {
							metext = metext.replace(value, '<img class="expimg" src="'+window.rootPath+'/images/emoji/' + emojiJson[value] + '.png" >');
							return metext;
						}
					}
				});
			}
			
		return metext;
};	

		//隐藏发送消息加载
		util.countMessage = function(allMessage,obj,id,map){
			for(var i = 0; i < obj.length; i++ ){
				if(obj[i].id == id){
					obj[i].sendState = 1;
					map[obj[i].to].sendState = 1;
					break;
				}
			}
			for(var i = 0; i < allMessage.length; i++){
				if(allMessage[i].id == id){
					allMessage[i].sendState = 1;
					break;
				}
			}
			return allMessage;
		};
		util.setProgress = function(obj){
			setTimeout(function(){
				for(var i = 0; i < obj.length; i++){
					if(obj[i].msgType != 11 && obj[i].sendState == 0){
						document.getElementById(obj[i].timestamp+'progressBar').style.display = 'block';
					}
				}
			},500);
			return;
		};
		
		util.serchImageMsg = function(obj,msg){
			for(var i = 0; i < obj.length; i++ ){
				if(obj[i].id == msg.id){
					obj[i].thumbContent = msg.thumbContent;
					obj[i].sourceURL = msg.sourceURL;
					obj[i].sendstats = 1;
				}
			}
					return obj;
		};
		util.checkSendStats = function(obj,timestamp,map){
			for(var i = 0; i < obj.length; i++){
				if(obj[i].msgType == 11){
					if((obj[i].sendState == 0) && (timestamp - obj[i].timestamp) > 6000){
						obj[i].sendState = 2;
						map[obj[i].to].sendState = 2;
						//console.log(obj[i].id+"状态改变为发送失败");
					}
				}
			}
			return obj;
		};
		
		util.countMessage2 = function(obj,id,mediaId){
			for(var i = 0; i < obj.length; i++ ){
				if(obj[i].id == id){
					obj[i].sendState = 3;
					obj[i].mediaId = mediaId;
					return obj[i];
				}
			}
			return null;
		};
		util.countMessage3 = function(obj,msg){
			for(var i = 0; i < obj.length; i++ ){
				if(obj[i].id == msg.id){
					obj[i].thumbContent = msg.thumbContent;
					return obj;
				}
			}
			return obj;
		};
		util.isimg=function(src)
		{
			var ext = [".bmp","jpg",".jpeg","tiff",".gif",".pcx",".tga",".exif",".fpx",".svg",".psd",".cdr",".pcd",".dxf",".ufo",".eps",".ai",".raw",".png"];
			var s = src.toLowerCase();
			var r = false;
			for(var i = 0; i < ext.length; i++)
			{
				if (s.indexOf(ext[i]) > 0)
				{
					//alert(ext[i]);
					r = true;
					break;
				}
			}	
			return r;
		};
		//消息通知
        var showWindow = null;
        var showWindowTimeOut = null;
		util.showMute = function(chatObj, unreadMsgCount){
            if(chatObj.messageContent == null || chatObj.messageContent.length == 0){
                return;
            }
			if (window.Notification.permission == "granted") {
                var title = unreadMsgCount > 0 ? '@work' + '('+unreadMsgCount+')' : '@work';
                if(showWindow != null){
                    showWindow.close();
                    clearTimeout(showWindowTimeOut);
                }
                var bodyContent = chatObj.name + ": " + chatObj.messageContent;
                var editAvatar =  '';
                if(chatObj.avatar && chatObj.avatar.length > 0){
                    editAvatar = editAvatar.concat(window.pcWeb.apiAddress, '/api/service/', chatObj.avatar, '&access_token=', window.pcWeb.user.access_token);
                }else{
                    var avatarPath = chatObj.isGroup ? '/images/goup_default.png' : '/images/oneps40.png';
                    editAvatar = chatObj.isGroup ? editAvatar.concat(window.rootPath, avatarPath) : editAvatar.concat(window.rootPath, avatarPath);
                }
                showWindow = new Notification(title, {icon: editAvatar, body: bodyContent});
                showWindow.onshow = function(){
                    showWindowTimeOut = setTimeout(function () {
                        showWindow.close();
                        return true;
                    }, 5000);
                };
                showWindow.onclick = function(){
                    //console.log("You Click The notification");
                    window.focus();
                };
            }else{
            	return false;
            }
		};
		//判断是否支持桌面通知
		util.supported = function(){
			if(window.Notification){
				//console.log("支持桌面通知");
				$("div#showMute").css('display','block');
				$("div#operaterBox").css('height','190px');
			} else {
				//console.log("不支持桌面通知");
				$("div#showMute").css('dispaly','none');
				$("div#operaterBox").css('height','154px');
			}
		};

		//判断浏览器是否最小化
	    util.isMinStatus = function() {
	        var isMin = false;
	        if (window.outerWidth != undefined) {
	        	isMin = window.outerWidth <= 160 && window.outerHeight <= 27;
	        }else {
	        	isMin = window.screenTop < -30000 && window.screenLeft < -30000;
	        }
	        return isMin;
	    };

        //页面中间圆点跟随点击
        util.getClickChatTop = function(clickElem) {
            clickElem = $(clickElem);
            var topVal = 145;
            var index = 0;
            while(true){
                index++;
                if(clickElem.attr('class').toString().indexOf('chatListColumn') > -1
                    || clickElem.attr('class').toString().indexOf('left_chat') > -1){
                    topVal += clickElem.position().top - $('#mainListContainer').scrollTop() + clickElem.height()/2-25;
                    break;
                }else{
                    clickElem = clickElem.parent();
                }
                if(index > 5) break;
            }
            return topVal;
	    };
		//接收消息声音
		util.msgPlay=function() {
				var myAuto = document.getElementById('msgaudio');
				myAuto.play();
				};
		
		util.merge = function(target, additional, deep, lastseen) {
		    var seen = lastseen || []
		      , depth = typeof deep == 'undefined' ? 2 : deep
		      , prop;

		    for (prop in additional) {
		      if (additional.hasOwnProperty(prop) && util.indexOf(seen, prop) < 0) {
		        if (typeof target[prop] !== 'object' || !depth) {
		          target[prop] = additional[prop];
		          seen.push(additional[prop]);
		        } else {
		          util.merge(target[prop], additional[prop], depth - 1, seen);
		        }
		      }
		    }

		    return target;
		};

		util.indexOf = function (arr, o, i) {

		    for (var j = arr.length, i = i < 0 ? i + j < 0 ? 0 : i + j : i || 0;
		         i < j && arr[i] !== o; i++) {}

		    return j <= i ? -1 : i;
		};
		
		util.chatScorllTop = function(){
			var chatScorll = $(".chatScorll>.chatContent")[0];
			chatScorll.scrollTop = chatScorll.scrollHeight; 
		};


		util.changeHeight = function(){
			bodyH = $(global).height();
			zH = bodyH * 0.84;
			$(".list,.chatContainer,.groupSetUp,.emptyBox").css({
				"height": zH
			});
			$(".ContainerBox").css({
				"height": zH - 119
			});
			$("#conversationContainer").css({
				"height": zH - 119
			});
			$("#contactListContainer").css({
				"height": zH - 119
			});
			$("#vernierContainer").css({
				"height": zH - 119
			});
			/*$(".chatScorll").css({
				"height": zH - 56
			});
			$(".chatScorll>.message").css({
				"height": zH - 98
			});*/
			$(".black").css({
				"height": bodyH
			});
			if (navigator.userAgent.indexOf('Firefox') >= 0)
			document.getElementById('footerWrap').style.bottom = '-10px';
		};

		util.timeFormat = function(time, isShowBeforeToday){
			time = moment(time);
			if(time.isValid()){
				if(moment().diff(time, 'days')>0){
					if(isShowBeforeToday) return "";
					return time.format("YYYY/M/D HH:mm");
				}else{
					return time.format("HH:mm");
				}
			}else{
				return time + "is invalid!";
			}
		};

    /**
     * server time
     *
     */
        var serverTime = null;
        var refreshTimeInterval = null;
        var reRequestInterval = null;
        var refreshTime = function(){
            var rate = 500;
            refreshTimeInterval = setInterval(function(){serverTime += rate;}, rate);
            reRequestInterval = setInterval(function(){serverTime = util.requestServerTime();}, 3 * 60 * 1000);
        };

        util.getServerTime = function(){
            return serverTime == null ? util.requestServerTime() : serverTime;
        }

        util.requestServerTime = function(){
            var xmlHttp=false;
            //获取服务器时间
            try{
                xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
            }catch(e){
            	try{
            		xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            	}catch(e2){xmlHttp=false;
                }
            }
            if(!xmlHttp&&typeof XMLHttpRequest != 'undefined'){
                xmlHttp = new XMLHttpRequest();
            }
            try{
                //连接服务器异常返回本地时间
                xmlHttp.open("GET","pages/server_date.jsp",false);
                xmlHttp.setRequestHeader("Range","bytes=-1");
                xmlHttp.send(null);
                var tempTime = new Date(xmlHttp.getResponseHeader("Date"));
                serverTime = tempTime.getTime();
                if(refreshTimeInterval == null) refreshTime();
                return serverTime;
            }catch (e){
                serverTime = new Date().getTime();
                if(refreshTimeInterval == null) refreshTime();
                return serverTime;
            }
        };

        /**
         * 文本框根据输入内容自适应高度
         * @param                {HTMLElement}        输入框元素
         * @param                {Number}                设置光标与输入框保持的距离(默认0)
         * @param                {Number}                设置最大高度(可选)
         */
        util.autoTextarea = function (elem, extra, maxHeight) {
            extra = extra || 0;
            var isFirefox = !!document.getBoxObjectFor || 'mozInnerScreenX' in window,
                isOpera = !!window.opera && !!window.opera.toString().indexOf('Opera'),
                addEvent = function (type, callback) {
                    elem.addEventListener ?
                        elem.addEventListener(type, callback, false) :
                        elem.attachEvent('on' + type, callback);
                },
                getStyle = elem.currentStyle ? function (name) {
                    var val = elem.currentStyle[name];

                    if (name === 'height' && val.search(/px/i) !== 1) {
                        var rect = elem.getBoundingClientRect();
                        return rect.bottom - rect.top -
                            parseFloat(getStyle('paddingTop')) -
                            parseFloat(getStyle('paddingBottom')) + 'px';
                    };

                    return val;
                } : function (name) {
                    return getComputedStyle(elem, null)[name];
                },
                minHeight = parseFloat(getStyle('height'));

            elem.style.resize = 'none';

            var change = function () {
                var scrollTop, height,
                    padding = 0,
                    style = elem.style;

                if (elem._length === elem.value.length) return;
                elem._length = elem.value.length;

                if (!isFirefox && !isOpera) {
                    padding = parseInt(getStyle('paddingTop')) + parseInt(getStyle('paddingBottom'));
                };
                scrollTop = document.body.scrollTop || document.documentElement.scrollTop;

                elem.style.height = minHeight + 'px';
                if (elem.scrollHeight > minHeight) {
                    if (maxHeight && elem.scrollHeight > maxHeight) {
                        height = maxHeight - padding;
                        style.overflowY = 'auto';
                    } else {
                        height = elem.scrollHeight - padding;
                        style.overflowY = 'hidden';
                    };
                    style.height = height + extra + 'px';
                    scrollTop += parseInt(style.height) - elem.currHeight;
                    document.body.scrollTop = scrollTop;
                    document.documentElement.scrollTop = scrollTop;
                    elem.currHeight = parseInt(style.height);

                    //设置DIV的高度
                    var inputDivHeight = elem.currHeight + 35;
                    elem.parentNode.parentNode.style.height = inputDivHeight + 'px';
                    document.getElementById('chatScorll').style.height = (500 - inputDivHeight) + 'px';
                }else{
                    elem.parentNode.parentNode.style.height = 67 + 'px';
                    document.getElementById('chatScorll').style.height = 433 + 'px';
                };
            };

            addEvent('propertychange', change);
            addEvent('input', change);
            addEvent('focus', change);
            change();
        };

        //重置聊天窗体样式
        util.resetChatBox = function(){
            document.getElementById('contentTextarea').style.height = 32 + 'px';
            document.getElementById('contentTextarea').parentNode.parentNode.style.height = 67 + 'px';
            document.getElementById('chatScorll').style.height = 433 + 'px';
        }

        //检查TOKEN是否过期
        util.tokenIsExpired = function (data) {
            return (data.errorObj && data.errorObj.errcode == '401');
        }

        //token无效处理
        util.tokenExpire = function(){
            swal({  title: "登录信息过期，请重新登录。",
                    showConfirmButton : true,
                    confirmButtonText: "确认",
                    closeOnConfirm: false },
                function () {
                    window.location = 'login.do';
                });
            return;
        }
	})(this.util={}, this);

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}